<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <base href="${basePath}">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" type="text/css" href="bootstrap/css/alertify.core.css">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/alertify.default.css">
    <link rel="stylesheet" type="text/css" href="Css/bootstrap-responsive.css"/>
       	<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-table.min.css">
    <link rel="stylesheet" type="text/css" href="Css/style.css"/>
    <link href="Css/jquery-ui.min.css" type="text/css" rel="stylesheet"/>
    <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/alertify.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap-table.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap-table-zh-CN.min.js"></script>
    <script type="text/javascript" src="js/ckform.js"></script>
    <script type="text/javascript" src="js/common.js"></script>
    <script type="text/javascript"
            src="js/jquery-ui.min.js"></script>

</head>
<body>
<form id="queryManagerForm" class="form-inline definewidth m20" action="/" method="post">
    <font color="#777777"><strong>管理员名称：</strong></font>
    <input type="text" name="userName" id="userName" class="abc input-default" placeholder="请输入管理员ID或者名称" value="${userName}">&nbsp;&nbsp;
    <button type="button" class="btn btn-primary"  onclick="newSearchManager();">查询</button>
  <!--   <button type="button" id="addnew" class="btn btn-primary" onclick="addManager()">添加管理员</button> -->
    <button type="button" id="addnew" class="btn btn-primary" onclick="addAgent()">添加游戏代理</button>
</form>
<table id="infoTable">

</table>
<div id="managerEditDiv" style="display: none;">
    <form action="/" method="post" id="addManagerForm">

        <table cellpadding="0" cellspacing="0">
            <tr>
                <td><label for="manager_type"><span
                        style="color:#F00; margin-right:2px;">*</span>管理员类型：
                </label>
                </td>
                <td>
                    <select id="manager_type" name="manager_type" class="sp_t">
                        <option value="0">二级代理</option>
                        <option value="2">一级代理</option>
                        <option value="1">主管理员</option>
                    </select>
                    </td>
            </tr>
            <tr>
                <td><label for="manager_account"><span
                        style="color:#F00; margin-right:2px;">*</span>管理员帐号：
                </label>
                </td>
                <td><input id="manager_account" name="manager_account" type='text' class="sp_t"
                           value=""/><span style="color: red">用于登录时使用</span></td>
            </tr>

            <tr>
                <td><label for="manager_name"><span
                        style="color:#F00; margin-right:2px;">*</span>管理员名称：
                </label>
                </td>
                <td><input id="manager_name" name="manager_name" type='text' class="sp_t"
                           value=""/><span style="color: red">用于显示时使用</span></td>
            </tr>

        </table>
    </form>
</div>

<div class="modal fade" id="addClubModal" tabindex="-1" role="dialog" data-keyboard="false" aria-labelledby="addClubLable">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">添加游戏俱乐部</h4>
      </div>
      <div class="modal-body">
        <form id="club_form">
          <div class="form-group">
            <label for="recipient-name" class="control-label">俱乐部管理员</label>
            <div class="row">
            	<label class="col-md-3 col-md-offset-1">管理员id：</label>
            	<input type="text" name="clubManagerId" class="col-md-4" id="clubManagerId">
            </div>
             <div class="row">
            	<label class="col-md-3 col-md-offset-1">管理员名称：</label>
            	<input type="text" name="clubManagerName" class="col-md-4" id="clubManagerName">
            </div>
          </div>
          <div class="form-group">
            <label for="message-text" class="control-label">俱乐部信息:</label>
            <div class="row">
            	<label class="col-md-3 col-md-offset-1">俱乐部名称：</label>
            	<input type="text" name="clubName" class="col-md-4" id="clubName">
            </div>
             <div class="row" id="clubIdDiv" style="display: none;">
            	<label class="col-md-3 col-md-offset-1">俱乐部Id：</label>
            	<span type="text" name="clubId" id="clubId" style="color: red;font-weight: bold;">123</span>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="addClubBtn" onclick="addClub()">确定</button>
      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="addManagerModal" tabindex="-1" role="dialog" data-keyboard="false" aria-labelledby="addClubLable">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">添加管理员</h4>
      </div>
      <div class="modal-body">
        <form id="manager_from" class="form-horizontal">
        	<div>
	          <div class="form-group" >
	            	<label for="playerId" class="col-sm-4 control-label">玩家id：</label>
	            	<div class="col-sm-6">
	            		<input type="text" name="playerId" class="form-control" id="playerId">
	            	</div>
	            	<div class="col-sm-2">
	            		<button type="button" class="btn btn-default" style="padding: 3px 12px;" id="searchPlayerBtn" onclick="searchPlayerInfo()">查询</button>
	            	</div>
	            	
	          </div>
	          <div class="form-group" >
	          		<label for="playerName" class="col-sm-4 control-label">游戏名：</label>
	            	<div class="col-sm-6">
	            		<input type="text" name="playerName" disabled="disabled" class="form-control" id="playerName">
	            	</div>
	          </div>
          </div>
	          <div id="agent_managerInfo" style="display: none;">
	           <div class="form-group" >
	           		<label for="agentAccount" class="col-sm-4 control-label">管理员类型：</label>
	            	<div class="col-sm-8">
	            		<select type="text" name="managerType" class="form-control" id="managerType">
	            			<option value=0 selected="selected">二级代理</option>
	            			<option value=2>一级代理</option>
	            			<option value=1>主管理员</option>
	            		</select>
	            	</div>
	           		<label for="agentAccount" class="col-sm-4 control-label">管理员账号：</label>
	            	<div class="col-sm-8">
	            		<input type="text" name="agentAccount" class="form-control" id="agentAccount">
	            	</div>
	            	
	           </div>
	            <div class="form-group">
	           <label for="clubName" class="col-sm-4 control-label">俱乐部名称：</label>
	            	<div class="col-sm-8">
	            		<input type="text" name="clubName" class="form-control" id="clubName">
	            	</div>
	           </div>
           </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="addManagerBtn" onclick="addAgentInfo()">确定</button>
      </div>
    </div>
  </div>
</div>

<div id="addCoinDiv" style="display: none;">
    <form action="${basePath}agent/agentCoinOperate.html" method="post" id="addCoinForm" >
        <!-- <input id="user_id" name="user_id" type='hidden'  value=""/> -->
        <table cellpadding="0" cellspacing="0">
            <tr>

                <td><label for="user_id"><span
                        style="color:#F00; margin-right:2px;">*</span>代理ID：
                </label>
                </td>
                <td><input id="user_id" name="user_id" type='text' class="sp_t"
                           value="" readonly="readonly"/></td>
            </tr>

            <tr>
                <td><label for="mahjong_coin"><span
                        style="color:#F00; margin-right:2px;">*</span>钻石：
                </label>
                </td>
                <td><input id="mahjong_coin" name="mahjong_coin" type='text' class="sp_t"
                           value=""/></td>
            </tr>
        </table>
    </form>

</div>
</body>
<script type="text/javascript">
var sys=sys||{};
sys.context="${basePath}";
alertify.set({
	labels : {
		ok     : "确认",
		cancel : "取消"
	},
	delay : 5000,
	buttonReverse : false,
	buttonFocus   : "ok"
});
	$(function(){
		$('#addClubModal').on('show.bs.modal', function (event) {
			  initAddClub();
			  var button = $(event.relatedTarget); // Button that triggered the modal
			  var managerId = button.data('managerid'),managerName=button.data('managername'); // Extract info from data-* attributes
			  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
			  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
			  var modal = $(this);
			  if(managerId && managerName){
				  modal.find('#clubManagerId').val(managerId).prop("disabled",true);
				  modal.find('#clubManagerName').val(managerName).prop("disabled",true);
			  }
			});
		
		$("#manager_from").on("change","#playerId",function(){
			$("#manager_from").find("#playerName").val();
			$("#addManagerBtn").removeData("manager");
		});
		loadTable();
	});
	
	function loadTable(){
		$('#infoTable').bootstrapTable({
			url: sys.context+'club/getManagerTable.html',
			method: 'post',
			cache: false,
			pagination: true,
			search:true,
			undefinedText:'',
			striped:true,
			queryParamsType:'free',
			queryParams: function (params) {
				console.log(params);
				params['offset']=params.offset||1;
	           	return params;
	        },
			sidePagination: "server",
			pageNumber:1,
			pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],
		    columns: [{field: 'id',title: '代理ID',align: 'center',sortable:true},
		              {field: 'adminDesc',title: '备注',align: 'center',sortable:true},
		              {field: 'userName',title: '昵称',width: '8%',align: 'center',sortable:true},
		              {field: 'userAccount', title: '账号',align: 'center',sortable:true}, 
		              {field: 'playerId',title: '游戏ID',align: 'center',sortable:true}, 
		              {field: 'createTime',title: '创建时间',align: 'center',sortable:true,order:'desc'},
		              {field: 'parentManager',title: '上级管理',align: 'center',sortable:true},
		              {field: 'agentCoin',title: '财富值',align: 'center',sortable:true},
		              {field: 'userType',title: '管理员类型',align: 'center',sortable:true,
							formatter:function(v,r,i){
		        				return v==0?"二级代理":"<kbd>一级代理</kbd>";
		        	  		}
		              },
		              {field: 'todaySale',title: '今日售钻',align: 'center',sortable:true},
		              {field: 'totalBuy',title: '购钻总额',align: 'center',sortable:true},
		              {field: 'clubIdStr',title: '俱乐部ID',align: 'center',sortable:true,
		            	  formatter:function(v,r,i){
		            		  if(v){
		            			  	var vsp=v.split(",");
		            		  		var span='<span title="'+v.replace(new RegExp(",","g"),"&#13;")+'">'+(vsp.length>1?vsp[0]+"...":vsp[0])+'</span>';
		            		  		//创建正则RegExp对象    
			            	  		return span;
		            		  }
		            	  }
		              },
		              {field: 'clubStr',title: '俱乐部',width: '5%',align: 'center',sortable:true,order:'desc',
		            	  formatter:function(v,r,i){
		            		  if(v){
		            			  	var vsp=v.split(",");
		            		  		var span='<span title="'+v.replace(new RegExp(",","g"),"&#13;")+'">'+(vsp.length>1?vsp[0]+"...":vsp[0])+'</span>';
		            		  		//创建正则RegExp对象    
			            	  		return span;
		            		  }
		              	  }
		              },
		              {field: '_opt',title:'操作',align: 'left',
		            	  formatter:function(v,r,i){
		            		  return '<a href="javascript:void(0);" onclick="showCionDiv('+r['id']+',this)" class="btn btn-primary">加钻</a>'+
		            		  '<div class="btn-group ">'+
		    				  '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">其他 <span class="caret"></span></button>'+
		    				  '<ul class="dropdown-menu dropdown-menu-right">'
		    				  		+'<li><a href="javascript:void(0);" class="btn btn-success " onclick="changePwd('+r['id']+','+r['userAccount']+')">重置密码</a></li>'
		    				  		+'<li role="separator" class="divider"></li>'
		    				    	+'<li><a href="javascript:void(0);" class="btn btn-success" onclick="deleteManager('+r['id']+','+r['userAccount']+')">删除</a></li>'
		    				    	+'<li><a href="javascript:void(0);" class="btn btn-success" onclick="upOrDownLevel('+r['id']+')">'+(r['userType']==0?'升级':'降级')+'</a></li>'
		    				    	+'<li><a href="javascript:void(0);" class="btn btn-success" onclick="updateAdminDesc(\''+r['adminDesc']+'\','+r['id']+')">备注</a></li>'
		    				    	+'<li><a href="javascript:void(0);" class="btn btn-success" data-backdrop="static" data-toggle="modal" data-target="#addClubModal" data-managerId="'+r['id']+'"  data-managerName="'+r['userName']+'" >添加俱乐部</a></li>'
		    				  +'</ul>'
		    				+'</div>';
		            	  }
		              }
		    ],
		    data: [{
		    	userAccount: "-",
		    	userName: '-',
		    	playerId: '-',
		    	agentCoin: '-'
		    }]
		});
	}
	
	
	function upOrDownLevel(managerId){
		if(managerId){
			alertify.confirm("是否确认改变该管理员级别?",function(e){
				if(e){
					$.post(sys.context+"club/upOrDownLevel.html",{"managerId":managerId},function(data){
						if(data && !data.error){
							alertify.alert(data["msg"],function(){
								 var myform = document.getElementById("queryManagerForm");
							        myform.action = sys.context+"club/managerInfo.html";
							        myform.submit();
							});
						}else{
							alertify.alert(data["msg"]);
						}
					},"json");
				}else{
					alertify.error("您取消了操作!");
				}
			});
		}
	}
	function addClub(){
		
		var clubName=$("#clubName").val(),clubManagerId=$("#clubManagerId").val();
		if(!clubName || !clubManagerId){
			alert("请填写完整信息");
			return false;
		}
		var clubData={"clubName":clubName,"clubManagerId":clubManagerId};
		$.post(sys.context+"club/addClub.html",clubData,function(data){
			if(data){
				var result=$.parseJSON(data),club=result["data"];
				if(result["error"]){
					alert(result["msg"]);
					return false;
				}
				$("#clubIdDiv").show().find("#clubId").html(club["clubId"]);
				alert("俱乐部添加成功！请记好俱乐部ID:"+club["clubId"]);
				$('#addClubModal').modal('hide');
			}
		},"json");
		<%-- $.ajax({
			type: "POST",
			url:sys.context+"manager/addClub.html",
			data:clubData,
			dataType:"json",
			contentType:"application/json",
			success: function(data) {
				console.log(data);
			}
		}); --%>
	}
	function initAddClub(){
		$("#clubName").val("");
		$("#clubManagerId").val("");
		$("#clubId").html("");
		$("#addClubDiv").hide();
	}
    function searchManager(){
        var myform = document.getElementById("queryManagerForm");
        myform.action = sys.context+"club/managerInfo.html";
        myform.submit();
    }
    function newSearchManager(){
        var searchkey=$("#queryManagerForm").find("#userName").val();
        $('#infoTable').bootstrapTable('refresh',{silent: true,query:{searchText:searchkey}});
    }
    function addManager(){
        $("#managerEditDiv").dialog({
            title: "添加管理员",
            height: 300,
            width: 400,
            modal: true,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close", $(this).parent()).hide();
            },
            buttons: {
                "确定": function () {
                   addManagerInfo()
                },
                "取消": function () {
                    resetAll();
                    $(this).dialog("close");
                }
            }
        });
    }

    function addManagerInfo() {
        var myform = document.getElementById("addManagerForm");
        myform.action = sys.context+"manager/addManager.html";
        myform.submit();


    }

    function deleteManager(id, account) {
        if (confirm("确认删除管理员？")) {
            $.ajax({
                type: "POST",
                url: sys.context+"manager/deleteManager.html",
                data: {
                    "user_id": id,
                },
                dataType: 'json',
                success: function (data) {
                    var row = data.effectRow;
                    if (row > 0) {
                        alert("删除成功");
                        $("tr[id=manager"+id+"]").remove();
                    }
                }
            });
        }
    }

    function changePwd(id, account) {
        if (confirm("确认重置密码？")) {
            $.ajax({
                type: "POST",
                url: sys.context+"manager/resetPwd.html",
                data: {
                    "user_id": id,
                },
                dataType: 'json',
                success: function (data) {
                    var row = data.effectRow;
                    if (row > 0) {
                        alert("密码重置成功");
                    }else{
                    	 alert("密码重置失败");
                    }
                }
            });
        }
    }


    function resetAll() {
        var myform = document.getElementById("addManagerForm");
        myform.reset();
    }
    
    function searchPlayerInfo(){
    	$("#addManagerBtn").removeData("manager");
    	$("#manager_from").find("#playerName").val("");
    	$("#manager_from").find("#agentAccount").val("");
    	$("#manager_from").find("#clubName").val("");
    	
		var playerId=$("#manager_from").find("#playerId").val();
		if(playerId){
			$.post(sys.context+"club/searchPlayerInfo.html",{"playerId":playerId},function(data){
				if(data){
					var result=$.parseJSON(data),player=result["player"],manager=result["manager"];
					if(!result["error"] && player){
						$("#manager_from").find("#playerName").val(player["nickName"]);
						$("#manager_from").find("#agent_managerInfo").show();
					}else if(player && result["error"]){
						$("#manager_from").find("#playerName").val(player["nickName"]);
						$("#manager_from").find("#agentAccount").val(manager["userAccount"]);
						alert("该玩家已经注册为管理员【"+manager["userName"]+"】");
						$("#addManagerBtn").data("manager",manager);
					}else if(result["msg"]){
						alert(data["msg"]);
					}
				}
			},"json");
		}
	}
    
    function addAgent(){
    	$("#addManagerModal").modal({"backdrop":"static"},'show');
    	$("#addManagerBtn").removeData("manager");
    	$("#manager_from").find("#playerId").val("");
    	$("#manager_from").find("#playerName").val("");
    	$("#manager_from").find("#agentAccount").val("");
    	$("#manager_from").find("#clubName").val("");
    	$("#manager_from").find("#agent_managerInfo").hide();
    }

    function addAgentInfo() {
    	var manager=$("#addManagerBtn").data("manager");
    	if(manager){
    		alert("该玩家已经注册为管理员【"+manager["userName"]+"】");
    		return false;
    	}
		var playerId=$("#manager_from").find("#playerId").val(),
		playerName=$("#manager_from").find("#playerName").val().trim(),
		agentAccount=$("#manager_from").find("#agentAccount").val(),
		clubName=$("#manager_from").find("#clubName").val()
		managerType=$("#manager_from").find("#managerType").val();
		if(playerId && playerName && agentAccount && clubName && managerType){
			var param={'playerId':playerId,'agentAccount':agentAccount,'clubName':clubName,"managerType":managerType};
			$.post(sys.context+"club/addAgent.html",param,function(data){
				var result=$.parseJSON(data),agent=result["agent"];
				if(agent){
					alert("添加管理员成功！账号是【"+agent["userAccount"]+"】");
					$("#addManagerBtn").data("manager",agent);
				}else if(result["error"] && result["msg"]){
					alert(result["msg"]);
				}
			},"json");
		}else{
			alert("填写的信息不完整!");
		}
    }
    
    //加砖div
    function showCionDiv(id,obj) {
        $("#user_id").val(id);
        //$("#agent_id").val(account)
        $("#addCoinDiv").dialog({
            title: "加砖",
            height: 300,
            width: 500,
            modal: true,
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close", $(this).parent()).hide();
            },
            buttons: {
                "确定": function () {
                    if (confirm("确认充值？")) {
                        addCoin(obj, $(this));
                    }

                },
                "取消": function () {
                    resetAll();
                    $(this).dialog("close");
                }
            }
        });
    }


    function addCoin(obj, obj1) {
        var parent = $(obj).parent().parent();

        $.ajax({
            type: "POST",
            url: sys.context+"agent/agentCoinAdd.html",
            data: {
                "orderUser": $("#user_id").val(),
                "tradeCoin": $("#mahjong_coin").val(),

            },
            dataType: 'json',
            success: function (data) {
                /*var row=data.effectRow;
                 if(row>0){
                 $(parent).find("td[name='mahjongCoin']").text(data.coinModel.mahjongCoin);
                 }*/
                 var id=$("#agentform").find("#id").val();
                 searchManager();
                resetAll();
                $(obj1).dialog("close");
            }
        });
    }

    function resetAll() {
        var myform = document.getElementById("addCoinForm");
        myform.reset();
    }
    
    function updateAdminDesc(defaultDesc,userId){
    	if(!userId){
    		alertify.error("用户ID为空!");
    		return false;
    	}
    	alertify.prompt("请输入备注", function (e, str) {
			if (e) {
				if(str && $.trim(str)){
					$.post(sys.context+"club/updateAdminDesc.html",{"desc":str,"userId":userId},function(data){
						alertify.alert(data["msg"],searchManager());
					},"json");
				}else{
					alertify.error("请完整输入");
				}
			} else {
				alertify.error("您取消了备注");
			}
			return false;
		}, defaultDesc);
    	
    }
</script>


</html>